import {uSelectCheckDataByQueryVo} from '@/api/singleParam'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import deepClone from '@/libs/deepClone'
import {Dayjs} from 'dayjs'
import {PropType} from 'vue'
import {ParamOfStatus} from '../image'
import {CnMediumSpan} from '../text'

type TableColumn = CColumn<SingleParam.CheckData>

export const ParamTable = defineComponent({
  props: {
    id: {
      type: String,
      required: true
    },
    dateRange: {
      type: Array as unknown as PropType<[Dayjs, Dayjs]>,
      required: true
    },
    paramStatus: {
      type: String,
      required: false
    },
    lazy: Boolean
  },
  emits: {
    'update:lazy': (data: false): boolean => true
  },
  setup(props, {emit}) {
    const {route} = useGlobalAPI()

    const state = reactive<{
      columns: TableColumn[]
      dataSource: SingleParam.CheckData[]
      pagation: Paging
      tableLoading: boolean
      tableTotal: number
    }>({
      columns: [
        {title: '指标', dataIndex: 'checkDataName'},
        {title: '状态', dataIndex: 'paramStatus'},
        {title: '数值', dataIndex: 'checkDataValue'},
        {title: '时间', dataIndex: 'checkTime'}
      ],
      dataSource: [],
      tableTotal: 0,
      pagation: {
        page: 1,
        size: 10
      },
      tableLoading: false
    })

    watch(
      () => state.columns,
      n => {
        // getColumnWidth()
      }
    )

    watch(
      () => props.lazy,
      n => {
        if (n) {
          state.pagation.page = 1
          getTableData()
          emit('update:lazy', false)
        }
      }
    )

    /**伸缩列方法 */
    // function getColumnWidth() {
    //   const table = document.getElementById(props.id) as HTMLElement | null
    //   if (!table) {
    //     return
    //   }
    //   const tableWidth = table.offsetWidth
    //   const columns = deepClone(state.columns) as typeof state.columns
    //   columns.forEach(
    //     column => !column.width && (column.width = (1 / state.columns.length) * tableWidth)
    //   )
    //   state.columns = columns
    // }

    function onResize() {
      // getColumnWidth()
    }

    const startAndEndTimeDispose = (obj: any) => {
      console.log(obj)

      let retObj = {
        startTime: '',
        endTime: ''
      }
      if (obj == null) {
      } else {
        if (obj[1] != '' && obj[0] != '') {
          retObj.startTime = obj[0].format('YYYY-MM-DD 00:00:00')
          retObj.endTime = obj[1].format('YYYY-MM-DD 23:59:59')
        }
      }
      return retObj
    }

    function getTableData(devId?: string, paramName?: string) {
      // eslint-disable-next-line no-param-reassign
      devId = devId || (route.query.devId as string)
      // eslint-disable-next-line no-param-reassign
      paramName = paramName || (route.query.paramName as string)
      if (!devId) {
        return
      }
      if (!paramName) {
        return
      }
      state.tableLoading = true
      const timeDataObj = startAndEndTimeDispose(props.dateRange)
      uSelectCheckDataByQueryVo({
        devId,
        paramName,
        page: state.pagation.page,
        size: state.pagation.size,
        startTime: timeDataObj.startTime,
        endTime: timeDataObj.endTime,
        paramStatus: props.paramStatus ? props.paramStatus : ''
      })
        .then(res => {
          if (res) {
            state.dataSource = res.data.list
            state.tableTotal = res.data.total
          }
          state.tableLoading = false
        })
        .catch(err => {
          state.tableLoading = false
        })
    }

    onMounted(async () => {
      getTableData()
      window.onresize = onResize
    })

    onUnmounted(() => {
      window.removeEventListener('resize', onResize)
    })

    return () => (
      <a-table
        id={props.id}
        columns={state.columns}
        dataSource={state.dataSource}
        loading={state.tableLoading}
        pagination={{
          position: 'bottom',
          current: state.pagation.page,
          pageSize: state.pagation.size,
          size: 'small',
          total: state.tableTotal,
          showTotal: (total: number) => `共 ${total} 条`,
          onChange: (page: number, size: number) => {
            state.pagation = {
              page,
              size
            }
            getTableData()
          }
        }}
      >
        {{
          bodyCell: ({text, record, index, column}: CBodyCell<SingleParam.CheckData>) => {
            switch (column.dataIndex) {
              case 'checkDataStatus':
                return (
                  <ParamOfStatus status={record.paramStatus}>
                    <CnMediumSpan class='text-14'>{record.paramStatus}</CnMediumSpan>
                  </ParamOfStatus>
                )
              case 'checkDataValue':
                return (
                  <CnMediumSpan class='text-14'>
                    {record.checkDataValue + ' ' + record.checkDataUnit}
                  </CnMediumSpan>
                )
              default:
                return <CnMediumSpan class='text-14'>{text}</CnMediumSpan>
            }
          }
        }}
      </a-table>
    )
  }
})
